package com.active.web;

import com.active.service.AjaxPageResult;
import com.active.service.listener.ProcessEndListener;
import com.active.service.listener.TaskAssigneeListener;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2019/6/14 0014.
 */
@RestController
@Slf4j
@RequestMapping("listener")
public class ListenerTestController {

    @Resource(name = "taskService")
    private TaskService taskService;

    @Resource(name = "runtimeService")
    private RuntimeService runtimeService;

    @Resource(name = "repositoryService")
    private RepositoryService repositoryService;

    @Resource(name = "identityService")
    private IdentityService identityService;

    @Resource(name = "historyService")
    private HistoryService historyService;

    @Resource(name = "formService")
    private FormService formService;

    @RequestMapping("test")
    public AjaxPageResult test(){

        Map<String, Object> map = new HashMap<>();

        map.put("endListener",new ProcessEndListener());
        map.put("assignmentDelegate",new TaskAssigneeListener());
        map.put("name","tianyu");
        //还有一个task参数，但是监听器里面有这个字段，在createTaskListener这个类里面，所以就不用put

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("listenerTest",map);
        //是否启动监听
        boolean bstart = (boolean)runtimeService.getVariable(processInstance.getId(),"setInStartListener");

        //流程图中指定的是liyunlong，但是在监听器里面修改为zhaogang了，测试一下是否修改成功
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskAssignee("zhaogang").singleResult();

        if(null == task){
            return AjaxPageResult.fail("修改指定执行人失败");
        }

        String value = (String)runtimeService.getVariable(processInstance.getId(),"setInTaskCreate");

        boolean bend = (boolean)runtimeService.getVariable(processInstance.getId(),"setInStartListener");

        //结束流程
        taskService.complete(task.getId());

        List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()).list();

        boolean cend = false;

        if(null != list && list.size() > 0){
            for(HistoricVariableInstance h : list){
                if(h.getVariableName().equals("setInStartListener")){
                    cend = true;
                    break;
                }
            }
        }
        return AjaxPageResult.success("测试完成，参数bstart："+bstart+",value:"+value+",bend:"+bend+"cend:"+cend);



    }


}
